﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using System.Net.Sockets;

namespace Ession
{
    /// <summary>
    /// 用于对某个URI发送请求并返回结果
    /// </summary>
    public class HttpRequest
    {
        public HttpRequest(string uri)
        {
            if (!uri.EndsWith("/"))
            {
                this.uri = uri + "/";
            }
            else
            {
                this.uri = uri;
            }
            PostData = new Dictionary<string, string>();
            //   RqtHeader = new Dictionary<string, string>();
            cookie = new CookieCollection();
            //RqtHeader = new Dictionary<string, string>();

            //#region 构造通常的请求头
            //RqtHeader.Add();
            //#endregion

            RespHeader = new Dictionary<string, string>();
            getHostAndResFromURI();
        }

        /// <summary>
        /// 响应数据长度
        /// </summary>
        public int ContentLength;
        /// <summary>
        /// 保存Cookie
        /// </summary>
        public CookieCollection cookie;

        /// <summary>
        /// 主机域名
        /// </summary>
        public string Host;

        /// <summary>
        /// Post数据
        /// </summary>
        public Dictionary<string, string> PostData;//= new Dictionary<string, string>();

        /// <summary>
        /// 相对资源地址
        /// </summary>
        public string UriRequest;


        private Socket ConnectSocket(string host, int port)
        {
            Socket s = null;
            IPHostEntry hostEntry = null;
            int i = host.IndexOf(":");
            if (i != -1)//有端口号
            {
                hostEntry = Dns.GetHostEntry(host.Substring(0, i));
            }
            else
            {
                hostEntry = Dns.GetHostEntry(host);
            }
            try
            {
                foreach (IPAddress address in hostEntry.AddressList)
                {
                    IPEndPoint ipe = new IPEndPoint(address, port);
                    Socket tempSocket =
                        new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    tempSocket.Connect(ipe);
                    if (tempSocket.Connected)
                    {
                        s = tempSocket;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                return s;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 得到请求头
        /// </summary>
        /// <returns></returns>
        private string GetHeader()
        {
            return "";
        }

        /// <summary>
        /// 从最原始的地址得到主机名和资源相对地址
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        private void getHostAndResFromURI()
        {
            string temp;
            Regex rex = new Regex(@"//.+?/");
            string result = rex.Match(uri).ToString();
            if (result != "")
            {
                Host = result.Substring(2, result.Length - 3);
            }
            string u = "";
            int i = uri.IndexOf(Host);
            u = uri.Substring(i + Host.Length);
            string t = System.Web.HttpUtility.UrlEncode(u);
            t = t.Replace("%2f", @"/");
            UriRequest = t;
        }

        /// <summary>
        /// 构造Post数据
        /// </summary>
        /// <returns></returns>
        string GetPostData()
        {
            return "";
        }


#region ProPerties

        /// <summary>
        ///  请求的URI 
        /// </summary>
        string uri;
        public string URI
        {
            get { return uri; }
            set { uri = value; }
        }

        /// <summary>
        /// 请求头
        /// </summary>
        public string RqtHeader;

        /// <summary>
        /// 返回头
        /// </summary>
        public Dictionary<string, string> RespHeader;

        public string ResponseData;

#endregion

#region Public Methods

        /// <summary>
        /// 发送请求(无Cookie),获取返回结果
        /// </summary>
        /// <returns></returns>
        public byte[] SendRequest()
        {
            byte[] tmpData=null;
            Socket s = ConnectSocket(Host, 80);

            RqtHeader = "GET " + UriRequest + " HTTP/1.1\r\nHost: " + Host + "\r\nAccept: */*\r\n" +
           "\r\nCache-Control: no-cache\r\nConnection: Keep-Alive\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; )\r\n\r\n";

            Byte[] bytesSent = Encoding.ASCII.GetBytes(RqtHeader);
            try
            {
                s.Send(bytesSent, bytesSent.Length, 0);

                //返回
                string Headerdata = "";
                byte[] tmpbytes = new byte[10];
                while (s.Receive(tmpbytes, 0, 1, SocketFlags.None) > 0)
                {
                    Headerdata += Encoding.ASCII.GetString(tmpbytes, 0, 1);
                    if (tmpbytes[0] == '\n' && Headerdata.EndsWith("\r\n\r\n"))
                        break;
                }
                //解析响应头
                ParseRespHeader(Headerdata);


                 tmpData = new byte[ContentLength];
                int bytes = 0;
                do
                {
                    bytes = s.Receive(tmpData, tmpData.Length, SocketFlags.None);

                } while (bytes > 0);

                return tmpData;
            }
            catch (Exception ex)
            {
                return tmpData;
            }

        }

        private void ParseRespHeader(string RespHeader)
        {
            string cl = "Content-Length:";
            string co = "Set-Cookie:";

            string[] d = RespHeader.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string line in d)
            {
                if (line.Contains(cl))//Content-Length头
                {
                    ContentLength = int.Parse(line.Substring(cl.Length));
                }
                if (line.Contains(co))
                {
                    string cook = line.Substring(co.Length);
                    int s = cook.IndexOf(";");
                    cook = cook.Substring(0, s + 1);

                    string[] co2 = cook.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    cookie.Add(new Cookie("f",co2[1]));               
                   
                }
            }
        }

        /// <summary>
        /// 发送请求(包括Cookie),获取返回结果
        /// </summary>
        /// <returns></returns>
        public string SendRequest(CookieCollection cookie)
        {
            return "";
        }

        /// <summary>
        /// 发送请求(包括Cookie,Post数据),获取返回结果
        /// </summary>
        /// <returns></returns>
        public string SendRequestAndPost(CookieCollection cookie)
        {
            return "";

        }

        /// <summary>
        /// 发送请求(无Cookie,Post数据),获取返回结果
        /// </summary>
        /// <returns></returns>
        public string SendRequestAndPost()
        {
            return "";

        }
#endregion
    }
}
